package com.offcn.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.offcn.bean.Blog;
import com.offcn.bean.EvaluateExample;
import com.offcn.bean.User;
import com.offcn.mapper.BlogMapper;
import com.offcn.mapper.EvaluateMapper;
import com.offcn.mapper.UserMapper;
import com.offcn.utils.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {
    private ReturnResult returnResult;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<Blog> getBlogPage(Integer pageNo) {
        PageHelper.startPage(pageNo,3);
        List<Blog> blogList = blogMapper.getBlogList(null);
        PageInfo<Blog> blogPageInfo = new PageInfo<>(blogList, 4);
        return blogPageInfo;
    }

    @Override
    @Transactional
    public void deleteBlogById(Integer bid) {
        //删除评论
        EvaluateExample evaluateExample = new EvaluateExample();
        evaluateExample.createCriteria().andBFkEqualTo(bid);
        int i = evaluateMapper.deleteByExample(evaluateExample);

        //删除博客
        int i1 = blogMapper.deleteByPrimaryKey(bid);
    }

    @Override
    public Blog getBlogUserByid(Integer bid) {
        //先将blog信息查询出来
        Blog blog = blogMapper.selectByPrimaryKey(bid);
        //查用户
        User user = userMapper.selectByPrimaryKey(blog.getuFk());
        blog.setUser(user);
        return blog;
    }

    @Override
    public ReturnResult addBlog(Blog blog, HttpSession session) {
        User user = (User) session.getAttribute("userSession");
        if(user!=null){
            try {
                blog.setuFk(user.getUid());
                blog.setDate(new Date());
                int insert = blogMapper.insert(blog);
                returnResult = new ReturnResult("【"+blog.getBtitle()+"】添加成功!",1,null);
            } catch (Exception e) {
                e.printStackTrace();
                returnResult = new ReturnResult("【"+blog.getBtitle()+"】添加失败!",-1,null);
            }
        }else{
            //未登录
            returnResult = new ReturnResult("请先登录后再操作!",-2,null);
        }
        return returnResult;
    }
}
